package Solution.problem054;

import java.util.ArrayList;
import java.util.List;

/**
 * @program Leetcode
 * @description: 转圈打印数组，边界控制
 * @author: lishangsheng
 * @create: 2019/05/29 09:53
 */
public class Solution {

    public static List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> nums = new ArrayList<Integer>();
        if (matrix == null) {
            return nums;
        }
        int rows = matrix.length;
        if (rows == 0) {
            return nums;
        }
        int cols = matrix[0].length;

        int rowStart = 0;
        int rowEnd = rows - 1;
        int colStart = 0;
        int colEnd = cols - 1;

        boolean isCols = true;
        boolean isAdd = true;
        int count = 1;
        for (int c = 0; c < cols; ) {
            for (int r = 0; r < rows; ) {
                nums.add(matrix[r][c]);


                //右上角
                if (count % 4 == 1 && isCols && r == rowStart && c == colEnd) {
                    isCols = false;
                    isAdd = true;
                    rowStart++;
                    /*记录转向数量*/
                    count++;
                }

                //最后一行最后一列,右下角
                if (count % 4 == 2 && !isCols && r == rowEnd && c == colEnd) {
                    isCols = true;
                    isAdd = false;
                    colEnd--;
                    count++;
                }

                //最后一行第一列,左下角
                if (count % 4 == 3 && isCols && r == rowEnd && c == colStart) {
                    isCols = false;
                    isAdd = false;
                    rowEnd--;
                    count++;
                }

                //左上角
                if (count % 4 == 0 && !isCols && r == rowStart && c == colStart) {
                    isCols = true;
                    isAdd = true;
                    colStart++;
                    count++;
                }


                if (rowStart > rowEnd || colStart > colEnd) {
                    return nums;
                }

                if (isCols) {
                    if (isAdd) {
                        c++;
                    } else {
                        c--;
                    }
                } else {
                    if (isAdd) {
                        r++;
                    } else {
                        r--;
                    }
                }
            }
        }

        return nums;
    }

    public static void main(String[] args){
        int[][] arys=new int[][]{{1,2,3},
                {4,5,6},{7, 8, 9}};

        int[][] arys2=new int[][]{{1,2,3,4},{5,6,7,8},{9,10,11,12}};
        List<Integer> integerList=spiralOrder(arys2);
        System.out.println(integerList);
    }
}
